import { useDeviceUuid } from "./useDeviceUuid";
import { useStorage } from "./useStorage";


export function httpPostV2<T = any>(url: string, postData: any, def: T | undefined = undefined): T {
    try {
        const HOST = "192.168.7.2"
        const PORT = 3000
        const token = useStorage().get('token', "")
        if (token) {
            postData['token'] = token;
        }
        const uuid = useDeviceUuid()
        if (uuid) {
            postData['uuid'] = uuid;
        }
        if (!url.startsWith('http')) {
            url = `http://${HOST}:${PORT}/${url}`;
        }
        const res = http.post(url, postData, {
            timeout: 5000,
            contentType: 'application/json'
        }) as AutoJs.Response;
        if (res.statusCode !== 200) {
            if (def) return def;
            throw new Error(`httpPost error: ${res.statusCode} ${res.statusMessage}`);
        }
        const contentType: string = (res.headers as any)["Content-Type"] || "";
        if (contentType.includes("text/html")) {
            if (def) return def;
            throw new Error(`httpPost error: ${res.body}`);
        }
        const body = res.body.json();
        const { message, success, data } = body;
        if (success) return data;
        if (def) return def;
        throw new Error(`httpPost error: ${message}`);
    } catch (e) {
        console.error((e as Error).toString())
        throw new Error((e as Error).toString())
    }
}